home *** CD-ROM | disk | FTP | other *** search
/ CD ROM Paradise Collection 4 / CD ROM Paradise Collection 4 1995 Nov.iso / clang / cweb31.zip / COMMON.W < prev    next >
Text File  |  1993-11-08  |  52KB  |  1,415 lines

  1. % This file is part of CWEB.
  2. % This program by Silvio Levy and Donald E. Knuth
  3. % is based on a program by Knuth.
  4. % It is distributed WITHOUT ANY WARRANTY, express or implied.
  5. % Version 3.1 --- November 1993
  6.  
  7. % Copyright (C) 1987,1990,1993 Silvio Levy and Donald E. Knuth
  8.  
  9. % Permission is granted to make and distribute verbatim copies of this
  10. % document provided that the copyright notice and this permission notice
  11. % are preserved on all copies.
  12.  
  13. % Permission is granted to copy and distribute modified versions of this
  14. % document under the conditions for verbatim copying, provided that the
  15. % entire resulting derived work is distributed under the terms of a
  16. % permission notice identical to this one.
  17.  
  18. \def\v{\char'174} % vertical (|) in typewriter font
  19.  
  20. \def\title{Common code for CTANGLE and CWEAVE (Version 3.1)}
  21. \def\topofcontents{\null\vfill
  22.   \centerline{\titlefont Common code for {\ttitlefont CTANGLE} and
  23.     {\ttitlefont CWEAVE}}
  24.   \vskip 15pt
  25.   \centerline{(Version 3.1)}
  26.   \vfill}
  27. \def\botofcontents{\vfill
  28. \noindent
  29. Copyright \copyright\ 1987, 1990, 1993 Silvio Levy and Donald E. Knuth
  30. \bigskip\noindent
  31. Permission is granted to make and distribute verbatim copies of this
  32. document provided that the copyright notice and this permission notice
  33. are preserved on all copies.
  34.  
  35. \smallskip\noindent
  36. Permission is granted to copy and distribute modified versions of this
  37. document under the conditions for verbatim copying, provided that the
  38. entire resulting derived work is distributed under the terms of a
  39. permission notice identical to this one.
  40. }
  41.  
  42. \pageno=\contentspagenumber \advance\pageno by 1
  43. \let\maybe=\iftrue
  44.  
  45. @** Introduction.  This file contains code common
  46. to both \.{CTANGLE} and \.{CWEAVE}, which roughly concerns the following
  47. problems: character uniformity, input routines, error handling and
  48. parsing of command line.  We have tried to concentrate in this file
  49. all the system dependencies, so as to maximize portability.
  50.  
  51. In the texts below we will
  52. sometimes use \.{CWEB} to refer to either of the two component
  53. programs, if no confusion can arise.
  54.  
  55. The file begins with a few basic definitions.
  56.  
  57. @c
  58. @<Include files@>@/
  59. @h
  60. @<Definitions that should agree with \.{CTANGLE} and \.{CWEAVE}@>@/
  61. @<Other definitions@>@/
  62. @<Predeclaration of procedures@>@/
  63.  
  64. @ In certain cases \.{CTANGLE} and \.{CWEAVE} should do almost, but not
  65. quite, the same thing.  In these cases we've written common code for
  66. both, differentiating between the two by means of the global variable
  67. |program|.
  68.  
  69. @d ctangle 0
  70. @d cweave 1
  71.  
  72. @<Definitions...@>=
  73. typedef short boolean;
  74. boolean program; /* \.{CWEAVE} or \.{CTANGLE}? */
  75.  
  76. @ \.{CWEAVE} operates in three phases: first it inputs the source
  77. file and stores cross-reference data, then it inputs the source once again and
  78. produces the \TEX/ output file, and finally it sorts and outputs the index.
  79. Similarly, \.{CTANGLE} operates in two phases.
  80. The global variable |phase| tells which phase we are in.
  81.  
  82. @<Other...@>= int phase; /* which phase are we in? */
  83.  
  84. @ There's an initialization procedure that gets both \.{CTANGLE} and
  85. \.{CWEAVE} off to a good start. We will fill in the details of this
  86. procedure later.
  87.  
  88. @c
  89. void
  90. common_init()
  91. {
  92.   @<Initialize pointers@>;
  93.   @<Set the default options common to \.{CTANGLE} and \.{CWEAVE}@>;
  94.   @<Scan arguments and open output files@>;
  95. }
  96.  
  97. @*1 The character set.
  98. \.{CWEB} uses the conventions of \CEE/ programs found in the standard
  99. \.{ctype.h} header file.
  100.  
  101. @<Include files@>=
  102. #include <ctype.h>
  103.  
  104. @ A few character pairs are encoded internally as single characters,
  105. using the definitions below. These definitions are consistent with
  106. an extension of ASCII code originally developed at MIT and explained in
  107. Appendix~C of {\sl The \TEX/book\/}; thus, users who have such a
  108. character set can type things like \.{\char'32} and \.{char'4} instead
  109. of \.{!=} and \.{\&\&}. (However, their files will not be too portable
  110. until more people adopt the extended code.)
  111.  
  112. If the character set is not ASCII, the definitions given here may conflict
  113. with existing characters; in such cases, other arbitrary codes should be
  114. substituted. The indexes to \.{CTANGLE} and \.{CWEAVE} mention every
  115. case where similar codes may have to be changed in order to
  116. avoid character conflicts. Look for the entry ``ASCII code dependencies''
  117. in those indexes.
  118.  
  119. @^ASCII code dependencies@>
  120. @^system dependencies@>
  121.  
  122. @d and_and 04 /* `\.{\&\&}'\,; corresponds to MIT's {\tentex\char'4} */
  123. @d lt_lt 020 /* `\.{<<}'\,;  corresponds to MIT's {\tentex\char'20} */
  124. @d gt_gt 021 /* `\.{>>}'\,;  corresponds to MIT's {\tentex\char'21} */
  125. @d plus_plus 013 /* `\.{++}'\,;  corresponds to MIT's {\tentex\char'13} */
  126. @d minus_minus 01 /* `\.{--}'\,;  corresponds to MIT's {\tentex\char'1} */
  127. @d minus_gt 031 /* `\.{->}'\,;  corresponds to MIT's {\tentex\char'31} */
  128. @d not_eq 032 /* `\.{!=}'\,;  corresponds to MIT's {\tentex\char'32} */
  129. @d lt_eq 034 /* `\.{<=}'\,;  corresponds to MIT's {\tentex\char'34} */
  130. @d gt_eq 035 /* `\.{>=}'\,;  corresponds to MIT's {\tentex\char'35} */
  131. @d eq_eq 036 /* `\.{==}'\,;  corresponds to MIT's {\tentex\char'36} */
  132. @d or_or 037 /* `\.{\v\v}'\,;  corresponds to MIT's {\tentex\char'37} */
  133. @d dot_dot_dot 016 /* `\.{...}'\,;  corresponds to MIT's {\tentex\char'16} */
  134. @d colon_colon 06 /* `\.{::}'\,;  corresponds to MIT's {\tentex\char'6} */
  135. @d period_ast 026 /* `\.{.*}'\,;  corresponds to MIT's {\tentex\char'26} */
  136. @d minus_gt_ast 027 /* `\.{->*}'\,;  corresponds to MIT's {\tentex\char'27} */
  137.  
  138. @** Input routines.  The lowest level of input to the \.{CWEB} programs
  139. is performed by |input_ln|, which must be told which file to read from.
  140. The return value of |input_ln| is 1 if the read is successful and 0 if
  141. not (generally this means the file has ended). The conventions
  142. of \TEX/ are followed; i.e., the characters of the next line of the file
  143. are copied into the |buffer| array,
  144. and the global variable |limit| is set to the first unoccupied position.
  145. Trailing blanks are ignored. The value of |limit| must be strictly less
  146. than |buf_size|, so that |buffer[buf_size-1]| is never filled.
  147.  
  148. Since |buf_size| is strictly less than |long_buf_size|,
  149. some of \.{CWEB}'s routines use the fact that it is safe to refer to
  150. |*(limit+2)| without overstepping the bounds of the array.
  151.  
  152. @d buf_size 100 /* for \.{CWEAVE} and \.{CTANGLE} */
  153. @d long_buf_size 500 /* for \.{CWEAVE} */
  154. @d xisspace(c) (isspace(c)&&((unsigned char)c<0200))
  155. @d xisupper(c) (isupper(c)&&((unsigned char)c<0200))
  156.  
  157. @<Definitions...@>=
  158. char buffer[long_buf_size]; /* where each line of input goes */
  159. char *buffer_end=buffer+buf_size-2; /* end of |buffer| */
  160. char *limit=buffer; /* points to the last character in the buffer */
  161. char *loc=buffer; /* points to the next character to be read from the buffer */
  162.  
  163. @ @<Include files@>=
  164. #include <stdio.h>
  165.  
  166. @ In the unlikely event that your standard I/O library does not
  167. support |feof|, |getc| and |ungetc| you may have to change things here.
  168. @^system dependencies@>
  169.  
  170. @c
  171. int input_ln(fp) /* copies a line into |buffer| or returns 0 */
  172. FILE *fp; /* what file to read from */
  173. {
  174.   register int  c=EOF; /* character read; initialized so some compilers won't complain */
  175.   register char *k;  /* where next character goes */
  176.   if (feof(fp)) return(0);  /* we have hit end-of-file */
  177.   limit = k = buffer;  /* beginning of buffer */
  178.   while (k<=buffer_end && (c=getc(fp)) != EOF && c!='\n')
  179.     if ((*(k++) = c) != ' ') limit = k;
  180.   if (k>buffer_end)
  181.     if ((c=getc(fp))!=EOF && c!='\n') {
  182.       ungetc(c,fp); loc=buffer; err_print("! Input line too long");
  183. @.Input line too long@>
  184.   }
  185.   if (c==EOF && limit==buffer) return(0);  /* there was nothing after
  186.     the last newline */
  187.   return(1);
  188. }
  189.  
  190. @ Now comes the problem of deciding which file to read from next.
  191. Recall that the actual text that \.{CWEB} should process comes from two
  192. streams: a |web_file|, which can contain possibly nested include
  193. commands \.{@@i}, and a |change_file|, which might also contain
  194. includes.  The |web_file| together with the currently open include
  195. files form a stack |file|, whose names are stored in a parallel stack
  196. |file_name|.  The boolean |changing| tells whether or not we're reading
  197. from the |change_file|.
  198.  
  199. The line number of each open file is also kept for error reporting and
  200. for the benefit of \.{CTANGLE}.
  201.  
  202. @f line x /* make |line| an unreserved word */
  203. @d max_include_depth 10 /* maximum number of source files open
  204.   simultaneously, not counting the change file */
  205. @d max_file_name_length 60
  206. @d cur_file file[include_depth] /* current file */
  207. @d cur_file_name file_name[include_depth] /* current file name */
  208. @d cur_line line[include_depth] /* number of current line in current file */
  209. @d web_file file[0] /* main source file */
  210. @d web_file_name file_name[0] /* main source file name */
  211.  
  212. @<Definitions...@>=
  213. int include_depth; /* current level of nesting */
  214. FILE *file[max_include_depth]; /* stack of non-change files */
  215. FILE *change_file; /* change file */
  216. char file_name[max_include_depth][max_file_name_length];
  217.   /* stack of non-change file names */
  218. char change_file_name[max_file_name_length]; /* name of change file */
  219. char alt_web_file_name[max_file_name_length]; /* alternate name to try */
  220. int line[max_include_depth]; /* number of current line in the stacked files */
  221. int change_line; /* number of current line in change file */
  222. int change_depth; /* where \.{@@y} originated during a change */
  223. boolean input_has_ended; /* if there is no more input */
  224. boolean changing; /* if the current line is from |change_file| */
  225. boolean web_file_open=0; /* if the web file is being read */
  226.  
  227. @ When |changing==0|, the next line of |change_file| is kept in
  228. |change_buffer|, for purposes of comparison with the next
  229. line of |cur_file|. After the change file has been completely input, we
  230. set |change_limit=change_buffer|,
  231. so that no further matches will be made.
  232.  
  233. Here's a shorthand expression for inequality between the two lines:
  234.  
  235. @d lines_dont_match (change_limit-change_buffer != limit-buffer ||
  236.   strncmp(buffer, change_buffer, limit-buffer))
  237.  
  238. @<Other...@>=
  239. char change_buffer[buf_size]; /* next line of |change_file| */
  240. char *change_limit; /* points to the last character in |change_buffer| */
  241.  
  242. @ Procedure |prime_the_change_buffer|
  243. sets |change_buffer| in preparation for the next matching operation.
  244. Since blank lines in the change file are not used for matching, we have
  245. |(change_limit==change_buffer && !changing)| if and only if
  246. the change file is exhausted. This procedure is called only when
  247. |changing| is 1; hence error messages will be reported correctly.
  248.  
  249. @c
  250. void
  251. prime_the_change_buffer()
  252. {
  253.   change_limit=change_buffer; /* this value is used if the change file ends */
  254.   @<Skip over comment lines in the change file; |return| if end of file@>;
  255.   @<Skip to the next nonblank line; |return| if end of file@>;
  256.   @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>;
  257. }
  258.  
  259. @ While looking for a line that begins with \.{@@x} in the change file, we
  260. allow lines that begin with \.{@@}, as long as they don't begin with \.{@@y},
  261. \.{@@z} or \.{@@i} (which would probably mean that the change file is fouled up).
  262.  
  263. @<Skip over comment lines in the change file...@>=
  264. while(1) {
  265.   change_line++;
  266.   if (!input_ln(change_file)) return;
  267.   if (limit<buffer+2) continue;
  268.   if (buffer[0]!='@@') continue;
  269.   if (xisupper(buffer[1])) buffer[1]=tolower(buffer[1]);
  270.   if (buffer[1]=='x') break;
  271.   if (buffer[1]=='y' || buffer[1]=='z' || buffer[1]=='i') {
  272.     loc=buffer+2;
  273.     err_print("! Missing @@x in change file");
  274. @.Missing @@x...@>
  275.   }
  276. }
  277.  
  278. @ Here we are looking at lines following the \.{@@x}.
  279.  
  280. @<Skip to the next nonblank line...@>=
  281. do {
  282.   change_line++;
  283.   if (!input_ln(change_file)) {
  284.     err_print("! Change file ended after @@x");
  285. @.Change file ended...@>
  286.     return;
  287.   }
  288. } while (limit==buffer);
  289.  
  290. @ @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>=
  291. {
  292.   change_limit=change_buffer-buffer+limit;
  293.   strncpy(change_buffer,buffer,limit-buffer+1);
  294. }
  295.  
  296. @ The following procedure is used to see if the next change entry should
  297. go into effect; it is called only when |changing| is 0.
  298. The idea is to test whether or not the current
  299. contents of |buffer| matches the current contents of |change_buffer|.
  300. If not, there's nothing more to do; but if so, a change is called for:
  301. All of the text down to the \.{@@y} is supposed to match. An error
  302. message is issued if any discrepancy is found. Then the procedure
  303. prepares to read the next line from |change_file|.
  304.  
  305. When a match is found, the current section is marked as changed unless
  306. the first line after the \.{@@x} and after the \.{@@y} both start with
  307. either |'@@*'| or |'@@ '| (possibly preceded by whitespace).
  308.  
  309. This procedure is called only when |buffer<limit|, i.e., when the
  310. current line is nonempty.
  311.  
  312. @d if_section_start_make_pending(b) {@+*limit='!';
  313.   for (loc=buffer;xisspace(*loc);loc++) ;
  314.   *limit=' ';
  315.   if (*loc=='@@' && (xisspace(*(loc+1)) || *(loc+1)=='*')) change_pending=b;
  316. }
  317.  
  318. @c
  319. void
  320. check_change() /* switches to |change_file| if the buffers match */
  321. {
  322.   int n=0; /* the number of discrepancies found */
  323.   if (lines_dont_match) return;
  324.   change_pending=0;
  325.   if (!changed_section[section_count]) {
  326.     if_section_start_make_pending(1);
  327.     if (!change_pending) changed_section[section_count]=1;
  328.   }
  329.   while (1) {
  330.     changing=1; print_where=1; change_line++;
  331.     if (!input_ln(change_file)) {
  332.       err_print("! Change file ended before @@y");
  333. @.Change file ended...@>
  334.       change_limit=change_buffer; changing=0;
  335.       return;
  336.     }
  337.     if (limit>buffer+1 && buffer[0]=='@@') {
  338.       if (xisupper(buffer[1])) buffer[1]=tolower(buffer[1]);
  339.       @<If the current line starts with \.{@@y},
  340.         report any discrepancies and |return|@>;
  341.     }
  342.     @<Move |buffer| and |limit|...@>;
  343.     changing=0; cur_line++;
  344.     while (!input_ln(cur_file)) { /* pop the stack or quit */
  345.       if (include_depth==0) {
  346.         err_print("! CWEB file ended during a change");
  347. @.CWEB file ended...@>
  348.         input_has_ended=1; return;
  349.       }
  350.       include_depth--; cur_line++;
  351.     }
  352.     if (lines_dont_match) n++;
  353.   }
  354. }
  355.  
  356. @ @<If the current line starts with \.{@@y}...@>=
  357. if (buffer[1]=='x' || buffer[1]=='z') {
  358.   loc=buffer+2; err_print("! Where is the matching @@y?");
  359. @.Where is the match...@>
  360.   }
  361. else if (buffer[1]=='y') {
  362.   if (n>0) {
  363.     loc=buffer+2;
  364.     printf("\n! Hmm... %d ",n);
  365.     err_print("of the preceding lines failed to match");
  366. @.Hmm... n of the preceding...@>
  367.   }
  368.   change_depth=include_depth;
  369.   return;
  370. }
  371.  
  372. @ The |reset_input| procedure, which gets \.{CWEB} ready to read the
  373. user's \.{CWEB} input, is used at the beginning of phase one of \.{CTANGLE},
  374. phases one and two of \.{CWEAVE}.
  375.  
  376. @c
  377. void
  378. reset_input()
  379. {
  380.   limit=buffer; loc=buffer+1; buffer[0]=' ';
  381.   @<Open input files@>;
  382.   include_depth=0; cur_line=0; change_line=0;
  383.   change_depth=include_depth;
  384.   changing=1; prime_the_change_buffer(); changing=!changing;
  385.   limit=buffer; loc=buffer+1; buffer[0]=' '; input_has_ended=0;
  386. }
  387.  
  388. @ The following code opens the input files.
  389. @^system dependencies@>
  390.  
  391. @<Open input files@>=
  392. if ((web_file=fopen(web_file_name,"r"))==NULL) {
  393.   strcpy(web_file_name,alt_web_file_name);
  394.   if ((web_file=fopen(web_file_name,"r"))==NULL)
  395.        fatal("! Cannot open input file ", web_file_name);
  396. }
  397. @.Cannot open input file@>
  398. @.Cannot open change file@>
  399. web_file_open=1;
  400. if ((change_file=fopen(change_file_name,"r"))==NULL)
  401.        fatal("! Cannot open change file ", change_file_name);
  402.  
  403. @ The |get_line| procedure is called when |loc>limit|; it puts the next
  404. line of merged input into the buffer and updates the other variables
  405. appropriately. A space is placed at the right end of the line.
  406. This procedure returns |!input_has_ended| because we often want to
  407. check the value of that variable after calling the procedure.
  408.  
  409. If we've just changed from the |cur_file| to the |change_file|, or if
  410. the |cur_file| has changed, we tell \.{CTANGLE} to print this
  411. information in the \CEE/ file by means of the |print_where| flag.
  412.  
  413. @d max_sections 2000 /* number of identifiers, strings, section names;
  414.   must be less than 10240 */
  415.  
  416. @<Defin...@>=
  417. typedef unsigned short sixteen_bits;
  418. sixteen_bits section_count; /* the current section number */
  419. boolean changed_section[max_sections]; /* is the section changed? */
  420. boolean change_pending; /* if the current change is not yet recorded in
  421.   |changed_section[section_count]| */
  422. boolean print_where=0; /* should \.{CTANGLE} print line and file info? */
  423.  
  424. @ @c
  425. int get_line() /* inputs the next line */
  426. {
  427.   restart:
  428.   if (changing && include_depth==change_depth)
  429.    @<Read from |change_file| and maybe turn off |changing|@>;
  430.   if (! changing || include_depth>change_depth) {
  431.     @<Read from |cur_file| and maybe turn on |changing|@>;
  432.     if (changing && include_depth==change_depth) goto restart;
  433.   }
  434.   loc=buffer; *limit=' ';
  435.   if (*buffer=='@@' && (*(buffer+1)=='i' || *(buffer+1)=='I')) {
  436.     loc=buffer+2;
  437.     while (loc<=limit && (*loc==' '||*loc=='\t'||*loc=='"')) loc++;
  438.     if (loc>=limit) {
  439.       err_print("! Include file name not given");
  440. @.Include file name ...@>
  441.       goto restart;
  442.     }
  443.     if (include_depth>=max_include_depth-1) {
  444.       err_print("! Too many nested includes");
  445. @.Too many nested includes@>
  446.       goto restart;
  447.     }
  448.     include_depth++; /* push input stack */
  449.     @<Try to open include file, abort push if unsuccessful, go to |restart|@>;
  450.   }
  451.   return (!input_has_ended);
  452. }
  453.  
  454. @ When an \.{@@i} line is found in the |cur_file|, we must temporarily
  455. stop reading it and start reading from the named include file.  The
  456. \.{@@i} line should give a complete file name with or without
  457. double quotes.
  458. If the environment variable \.{CWEBINPUTS} is set, or if the compiler flag
  459. of the same name was defined at compile time,
  460. \.{CWEB} will look for include files in the directory thus named, if
  461. it cannot find them in the current directory.
  462. (Colon-separated paths are not supported.)
  463. The remainder of the \.{@@i} line after the file name is ignored.
  464.  
  465. @d too_long() {include_depth--;
  466.         err_print("! Include file name too long"); goto restart;}
  467.  
  468. @<Include...@>=
  469. #include <stdlib.h> /* declaration of |getenv| and |exit| */
  470.  
  471. @ @<Try to open...@>= {
  472.   char temp_file_name[max_file_name_length];
  473.   char *cur_file_name_end=cur_file_name+max_file_name_length-1;
  474.   char *k=cur_file_name, *kk;
  475.   int l; /* length of file name */
  476.  
  477.   while (*loc!=' '&&*loc!='\t'&&*loc!='"'&&k<=cur_file_name_end) *k++=*loc++;
  478.   if (k>cur_file_name_end) too_long();
  479. @.Include file name ...@>
  480.   *k='\0';
  481.   if ((cur_file=fopen(cur_file_name,"r"))!=NULL) {
  482.     cur_line=0; print_where=1;
  483.     goto restart; /* success */
  484.   }
  485.   kk=getenv("CWEBINPUTS");
  486.   if (kk!=NULL) {
  487.     if ((l=strlen(kk))>max_file_name_length-2) too_long();
  488.     strcpy(temp_file_name,kk);
  489.   }
  490.   else {
  491. #ifdef CWEBINPUTS
  492.     if ((l=strlen(CWEBINPUTS))>max_file_name_length-2) too_long();
  493.     strcpy(temp_file_name,CWEBINPUTS);
  494. #else
  495.     l=0;
  496. #endif /* |CWEBINPUTS| */
  497.   }
  498.   if (l>0) {
  499.     if (k+l+2>=cur_file_name_end)  too_long();
  500. @.Include file name ...@>
  501.     for (; k>= cur_file_name; k--) *(k+l+1)=*k;
  502.     strcpy(cur_file_name,temp_file_name);
  503.     cur_file_name[l]='/'; /* \UNIX/ pathname separator */
  504.     if ((cur_file=fopen(cur_file_name,"r"))!=NULL) {
  505.       cur_line=0; print_where=1;
  506.       goto restart; /* success */
  507.     }
  508.   }
  509.   include_depth--; err_print("! Cannot open include file"); goto restart;
  510. }
  511.  
  512. @ @<Read from |cur_file|...@>= {
  513.   cur_line++;
  514.   while (!input_ln(cur_file)) { /* pop the stack or quit */
  515.     print_where=1;
  516.     if (include_depth==0) {input_has_ended=1; break;}
  517.     else {
  518.       fclose(cur_file); include_depth--;
  519.       if (changing && include_depth==change_depth) break;
  520.       cur_line++;
  521.     }
  522.   }
  523.   if (!changing && !input_has_ended)
  524.    if (limit-buffer==change_limit-change_buffer)
  525.     if (buffer[0]==change_buffer[0])
  526.       if (change_limit>change_buffer) check_change();
  527. }
  528.  
  529. @ @<Read from |change_file|...@>= {
  530.   change_line++;
  531.   if (!input_ln(change_file)) {
  532.     err_print("! Change file ended without @@z");
  533. @.Change file ended...@>
  534.     buffer[0]='@@'; buffer[1]='z'; limit=buffer+2;
  535.   }
  536.   if (limit>buffer) { /* check if the change has ended */
  537.     if (change_pending) {
  538.       if_section_start_make_pending(0);
  539.       if (change_pending) {
  540.         changed_section[section_count]=1; change_pending=0;
  541.       }
  542.     }
  543.     *limit=' ';
  544.     if (buffer[0]=='@@') {
  545.       if (xisupper(buffer[1])) buffer[1]=tolower(buffer[1]);
  546.       if (buffer[1]=='x' || buffer[1]=='y') {
  547.         loc=buffer+2;
  548.         err_print("! Where is the matching @@z?");
  549. @.Where is the match...@>
  550.       }
  551.       else if (buffer[1]=='z') {
  552.         prime_the_change_buffer(); changing=!changing; print_where=1;
  553.       }
  554.     }
  555.   }
  556. }
  557.  
  558. @ At the end of the program, we will tell the user if the change file
  559. had a line that didn't match any relevant line in |web_file|.
  560.  
  561. @c
  562. void
  563. check_complete(){
  564.   if (change_limit!=change_buffer) { /* |changing| is 0 */
  565.     strncpy(buffer,change_buffer,change_limit-change_buffer+1);
  566.     limit=buffer+(int)(change_limit-change_buffer);
  567.     changing=1; change_depth=include_depth; loc=buffer;
  568.     err_print("! Change file entry did not match");
  569. @.Change file entry did not match@>
  570.   }
  571. }
  572.  
  573. @** Storage of names and strings.
  574. Both \.{CWEAVE} and \.{CTANGLE} store identifiers, section names and
  575. other strings in a large array of |char|s, called |byte_mem|.
  576. Information about the names is kept in the array |name_dir|, whose
  577. elements are structures of type |name_info|, containing a pointer into
  578. the |byte_mem| array (the address where the name begins) and other data.
  579. A |name_pointer| variable is a pointer into |name_dir|.
  580.  
  581. @d max_bytes 90000 /* the number of bytes in identifiers,
  582.   index entries, and section names; must be less than $2^{24}$ */
  583. @d max_names 4000 /* number of identifiers, strings, section names;
  584.   must be less than 10240 */
  585.  
  586. @<Definitions that...@>=
  587. typedef struct name_info {
  588.   char *byte_start; /* beginning of the name in |byte_mem| */
  589.   @<More elements of |name_info| structure@>@;
  590. } name_info; /* contains information about an identifier or section name */
  591. typedef name_info *name_pointer; /* pointer into array of |name_info|s */
  592. char byte_mem[max_bytes]; /* characters of names */
  593. char *byte_mem_end = byte_mem+max_bytes-1; /* end of |byte_mem| */
  594. name_info name_dir[max_names]; /* information about names */
  595. name_pointer name_dir_end = name_dir+max_names-1; /* end of |name_dir| */
  596.  
  597. @ The actual sequence of characters in the name pointed to by a |name_pointer
  598. p| appears in positions |p->byte_start| to |(p+1)->byte_start-1|, inclusive.
  599. The |print_id| macro prints this text on the user's terminal.
  600.  
  601. @d length(c) (c+1)->byte_start-(c)->byte_start /* the length of a name */
  602. @d print_id(c) term_write((c)->byte_start,length((c))) /* print identifier */
  603.  
  604. @ The first unused position in |byte_mem| and |name_dir| is
  605. kept in |byte_ptr| and |name_ptr|, respectively.  Thus we
  606. usually have |name_ptr->byte_start==byte_ptr|, and certainly
  607. we want to keep |name_ptr<=name_dir_end| and |byte_ptr<=byte_mem_end|.
  608.  
  609. @<Defini...@>=
  610. name_pointer name_ptr; /* first unused position in |byte_start| */
  611. char *byte_ptr; /* first unused position in |byte_mem| */
  612.  
  613. @ @<Init...@>=
  614. name_dir->byte_start=byte_ptr=byte_mem; /* position zero in both arrays */
  615. name_ptr=name_dir+1; /* |name_dir[0]| will be used only for error recovery */
  616. name_ptr->byte_start=byte_mem; /* this makes name 0 of length zero */
  617.  
  618. @ The names of identifiers are found by computing a hash address |h| and
  619. then looking at strings of bytes signified by the |name_pointer|s
  620. |hash[h]|, |hash[h]->link|, |hash[h]->link->link|, \dots,
  621. until either finding the desired name or encountering the null pointer.
  622.  
  623. @<More elements of |name...@>=
  624. struct name_info *link;
  625.  
  626. @ The hash table itself
  627. consists of |hash_size| entries of type |name_pointer|, and is
  628. updated by the |id_lookup| procedure, which finds a given identifier
  629. and returns the appropriate |name_pointer|. The matching is done by the
  630. function |names_match|, which is slightly different in
  631. \.{CWEAVE} and \.{CTANGLE}.  If there is no match for the identifier,
  632. it is inserted into the table.
  633.  
  634. @d hash_size 353 /* should be prime */
  635.  
  636. @<Defini...@>=
  637. typedef name_pointer *hash_pointer;
  638. name_pointer hash[hash_size]; /* heads of hash lists */
  639. hash_pointer hash_end = hash+hash_size-1; /* end of |hash| */
  640. hash_pointer h; /* index into hash-head array */
  641.  
  642. @ @<Predec...@>=
  643. extern int names_match();
  644.  
  645. @ Initially all the hash lists are empty.
  646.  
  647. @<Init...@>=
  648. for (h=hash; h<=hash_end; *h++=NULL) ;
  649.  
  650. @ Here is the main procedure for finding identifiers:
  651.  
  652. @c
  653. name_pointer
  654. id_lookup(first,last,t) /* looks up a string in the identifier table */
  655. char *first; /* first character of string */
  656. char *last; /* last character of string plus one */
  657. char t; /* the |ilk|; used by \.{CWEAVE} only */
  658. {
  659.   char *i=first; /* position in |buffer| */
  660.   int h; /* hash code */
  661.   int l; /* length of the given identifier */
  662.   name_pointer p; /* where the identifier is being sought */
  663.   if (last==NULL) for (last=first; *last!='\0'; last++);
  664.   l=last-first; /* compute the length */
  665.   @<Compute the hash code |h|@>;
  666.   @<Compute the name location |p|@>;
  667.   if (p==name_ptr) @<Enter a new name into the table at position |p|@>;
  668.   return(p);
  669. }
  670.  
  671. @ A simple hash code is used: If the sequence of
  672. character codes is $c_1c_2\ldots c_n$, its hash value will be
  673. $$(2^{n-1}c_1+2^{n-2}c_2+\cdots+c_n)\,\bmod\,|hash_size|.$$
  674.  
  675. @<Compute the hash...@>=
  676. h=(unsigned char)*i;
  677. while (++i<last) h=(h+h+(int)((unsigned char)*i)) % hash_size;
  678. @^high-bit character handling@>
  679.  
  680. @ If the identifier is new, it will be placed in position |p=name_ptr|,
  681. otherwise |p| will point to its existing location.
  682.  
  683. @<Compute the name location...@>=
  684. p=hash[h];
  685. while (p && !names_match(p,first,l,t)) p=p->link;
  686. if (p==NULL) {
  687.   p=name_ptr; /* the current identifier is new */
  688.   p->link=hash[h]; hash[h]=p; /* insert |p| at beginning of hash list */
  689. }
  690.  
  691. @ The information associated with a new identifier must be initialized
  692. in a slightly different way in \.{CWEAVE} than in \.{CTANGLE}; hence the
  693. |init_p| procedure.
  694.  
  695. @<Pred...@>=
  696. void init_p();
  697.  
  698. @ @<Enter a new name...@>= {
  699.   if (byte_ptr+l>byte_mem_end) overflow("byte memory");
  700.   if (name_ptr>=name_dir_end) overflow("name");
  701.   strncpy(byte_ptr,first,l);
  702.   (++name_ptr)->byte_start=byte_ptr+=l;
  703.   if (program==cweave) init_p(p,t);
  704. }
  705.  
  706. @ The names of sections are stored in |byte_mem| together
  707. with the identifier names, but a hash table is not used for them because
  708. \.{CTANGLE} needs to be able to recognize a section name when given a prefix of
  709. that name. A conventional binary search tree is used to retrieve section names,
  710. with fields called |llink| and |rlink| (where |llink| takes the place
  711. of |link|).  The root of this tree is stored in |name_dir->rlink|;
  712. this will be the only information in |name_dir[0]|.
  713.  
  714. Since the space used by |rlink| has a different function for
  715. identifiers than for section names, we declare it as a |union|.
  716.  
  717. @d llink link /* left link in binary search tree for section names */
  718. @d rlink dummy.Rlink /* right link in binary search tree for section names */
  719. @d root name_dir->rlink /* the root of the binary search tree
  720.   for section names */
  721.  
  722. @<More elements of |name...@>=
  723. union {
  724.   struct name_info *Rlink; /* right link in binary search tree for section
  725.     names */
  726.   char Ilk; /* used by identifiers in \.{CWEAVE} only */
  727. } dummy;
  728.  
  729. @ @<Init...@>=
  730. root=NULL; /* the binary search tree starts out with nothing in it */
  731.  
  732. @ If |p| is a |name_pointer| variable, as we have seen,
  733. |p->byte_start| is the beginning of the area where the name
  734. corresponding to |p| is stored.  However, if |p| refers to a section
  735. name, the name may need to be stored in chunks, because it may
  736. ``grow'': a prefix of the section name may be encountered before
  737. the full name.  Furthermore we need to know the length of the shortest
  738. prefix of the name that was ever encountered.
  739.  
  740. We solve this problem by inserting two extra bytes at |p->byte_start|,
  741. representing the length of the shortest prefix, when |p| is a
  742. section name. Furthermore, the last byte of the name will be a blank
  743. space if |p| is a prefix. In the latter case, the name pointer
  744. |p+1| will allow us to access additional chunks of the name:
  745. The second chunk will begin at the name pointer |(p+1)->link|,
  746. and if it too is a prefix (ending with blank) its |link| will point
  747. to additional chunks in the same way. Null links are represented by
  748. |name_dir|.
  749.  
  750. @d first_chunk(p)  ((p)->byte_start+2)
  751. @d prefix_length(p) (int)((unsigned char)*((p)->byte_start)*256 +
  752.                 (unsigned char)*((p)->byte_start+1))
  753. @d set_prefix_length(p,m) (*((p)->byte_start)=(m)/256,
  754.                  *((p)->byte_start+1)=(m)%256)
  755.  
  756. @c
  757. void
  758. print_section_name(p)
  759. name_pointer p;
  760. {
  761.   char *ss, *s = first_chunk(p);
  762.   name_pointer q = p+1;
  763.   while (p!=name_dir) {
  764.     ss = (p+1)->byte_start-1;
  765.     if (*ss==' ' && ss>=s) {
  766.       term_write(s,ss-s); p=q->link; q=p;
  767.     } else {
  768.       term_write(s,ss+1-s); p=name_dir; q=NULL;
  769.     }
  770.     s = p->byte_start;
  771.   }
  772.   if (q) term_write("...",3); /* complete name not yet known */
  773. }
  774.  
  775. @ @c
  776. void
  777. sprint_section_name(dest,p)
  778.   char*dest;
  779.   name_pointer p;
  780. {
  781.   char *ss, *s = first_chunk(p);
  782.   name_pointer q = p+1;
  783.   while (p!=name_dir) {
  784.     ss = (p+1)->byte_start-1;
  785.     if (*ss==' ' && ss>=s) {
  786.       p=q->link; q=p;
  787.     } else {
  788.       ss++; p=name_dir;
  789.     }
  790.     strncpy(dest,s,ss-s), dest+=ss-s;
  791.     s = p->byte_start;
  792.   }
  793.   *dest='\0';
  794. }
  795.  
  796. @ @c
  797. void
  798. print_prefix_name(p)
  799. name_pointer p;
  800. {
  801.   char *s = first_chunk(p);
  802.   int l = prefix_length(p);
  803.   term_write(s,l);
  804.   if (s+l<(p+1)->byte_start) term_write("...",3);
  805. }
  806.  
  807. @ When we compare two section names, we'll need a function analogous to
  808. |strcmp|. But we do not assume the strings
  809. are null-terminated, and we keep an eye open for prefixes and extensions.
  810.  
  811. @d less 0 /* the first name is lexicographically less than the second */
  812. @d equal 1 /* the first name is equal to the second */
  813. @d greater 2 /* the first name is lexicographically greater than the second */
  814. @d prefix 3 /* the first name is a proper prefix of the second */
  815. @d extension 4 /* the first name is a proper extension of the second */
  816.  
  817. @c
  818. int web_strcmp(j,j_len,k,k_len) /* fuller comparison than |strcmp| */
  819.   char *j, *k; /* beginning of first and second strings */
  820.   int j_len, k_len; /* length of strings */
  821. {
  822.   char *j1=j+j_len, *k1=k+k_len;
  823.   while (k<k1 && j<j1 && *j==*k) k++, j++;
  824.   if (k==k1) if (j==j1) return equal;
  825.     else return extension;
  826.   else if (j==j1) return prefix;
  827.   else if (*j<*k) return less;
  828.   else return greater;
  829. }
  830.  
  831. @ Adding a section name to the tree is straightforward if we know its
  832. parent and whether it's the |rlink| or |llink| of the parent.  As a
  833. special case, when the name is the first section being added, we set the
  834. ``parent'' to |NULL|.  When a section name is created, it has only one
  835. chunk, which however may be just a prefix: the full name will
  836. hopefully be unveiled later.  Obviously, |prefix_length| starts
  837. out as the length of the first chunk, though it may decrease later.
  838.  
  839. The information associated with a new node must be initialized
  840. differently in \.{CWEAVE} and \.{CTANGLE}; hence the
  841. |init_node| procedure, which is defined differently in \.{cweave.w}
  842. and \.{ctangle.w}.
  843.  
  844. @<Prede...@>=
  845. extern void init_node();
  846.  
  847. @ @c
  848. name_pointer
  849. add_section_name(par,c,first,last,ispref) /* install a new node in the tree */
  850. name_pointer par; /* parent of new node */
  851. int c; /* right or left? */
  852. char *first; /* first character of section name */
  853. char *last; /* last character of section name, plus one */
  854. int ispref; /* are we adding a prefix or a full name? */
  855. {
  856.   name_pointer p=name_ptr; /* new node */
  857.   char *s=first_chunk(p);
  858.   int name_len=last-first+ispref; /* length of section name */
  859.   if (s+name_len>byte_mem_end) overflow("byte memory");
  860.   if (name_ptr+1>=name_dir_end) overflow("name");
  861.   (++name_ptr)->byte_start=byte_ptr=s+name_len;
  862.   if (ispref) {
  863.     *(byte_ptr-1)=' ';
  864.     name_len--;
  865.     name_ptr->link=name_dir;
  866.     (++name_ptr)->byte_start=byte_ptr;
  867.   }
  868.   set_prefix_length(p,name_len);
  869.   strncpy(s,first,name_len);
  870.   p->llink=NULL;
  871.   p->rlink=NULL;
  872.   init_node(p);
  873.   return par==NULL ? (root=p) : c==less ? (par->llink=p) : (par->rlink=p);
  874. }
  875.  
  876. @ @c
  877. void
  878. extend_section_name(p,first,last,ispref)
  879. name_pointer p; /* name to be extended */
  880. char *first; /* beginning of extension text */
  881. char *last; /* one beyond end of extension text */
  882. int ispref; /* are we adding a prefix or a full name? */
  883. {
  884.   char *s;
  885.   name_pointer q=p+1;
  886.   int name_len=last-first+ispref;
  887.   if (name_ptr>=name_dir_end) overflow("name");
  888.   while (q->link!=name_dir) q=q->link;
  889.   q->link=name_ptr;
  890.   s=name_ptr->byte_start;
  891.   name_ptr->link=name_dir;
  892.   if (s+name_len>byte_mem_end) overflow("byte memory");
  893.   (++name_ptr)->byte_start=byte_ptr=s+name_len;
  894.   strncpy(s,first,name_len);
  895.   if (ispref) *(byte_ptr-1)=' ';
  896. }
  897.  
  898. @ The |section_lookup| procedure is supposed to find a
  899. section name that matches a new name, installing the new name if
  900. its doesn't match an existing one. The new name is the string
  901. between |first| and |last|; a ``match'' means that the new name
  902. exactly equals or is a prefix or extension of a name in the tree.
  903.  
  904. @c
  905. name_pointer
  906. section_lookup(first,last,ispref) /* find or install section name in tree */
  907. char *first, *last; /* first and last characters of new name */
  908. int ispref; /* is the new name a prefix or a full name? */
  909. {
  910.   int c=0; /* comparison between two names; initialized so some compilers won't complain */
  911.   name_pointer p=root; /* current node of the search tree */
  912.   name_pointer q=NULL; /* another place to look in the tree */
  913.   name_pointer r=NULL; /* where a match has been found */
  914.   name_pointer par=NULL; /* parent of |p|, if |r| is |NULL|;
  915.             otherwise parent of |r| */
  916.   int name_len=last-first+1;
  917.   @<Look for matches for new name among shortest prefixes, complaining
  918.         if more than one is found@>;
  919.   @<If no match found, add new name to tree@>;
  920.   @<If one match found, check for compatibility and return match@>;
  921. }
  922.  
  923. @ A legal new name matches an existing section name if and only if it
  924. matches the shortest prefix of that section name.  Therefore we can
  925. limit our search for matches to shortest prefixes, which eliminates
  926. the need for chunk-chasing at this stage.
  927.  
  928. @<Look for matches for new name among...@>=
  929. while (p) { /* compare shortest prefix of |p| with new name */
  930.   c=web_strcmp(first,name_len,first_chunk(p),prefix_length(p));
  931.   if (c==less || c==greater) { /* new name does not match |p| */
  932.     if (r==NULL) /* no previous matches have been found */
  933.       par=p;
  934.     p=(c==less?p->llink:p->rlink);
  935.   } else { /* new name matches |p| */
  936.     if (r!=NULL) {  /* and also |r|: illegal */
  937.       printf("\n! Ambiguous prefix: matches <");
  938. @.Ambiguous prefix ... @>
  939.       print_prefix_name(p);
  940.       printf(">\n and <");
  941.       print_prefix_name(r);
  942.       err_print(">");
  943.       return name_dir; /* the unsection */
  944.     }
  945.     r=p; /* remember match */
  946.     p=p->llink; /* try another */
  947.     q=r->rlink; /* we'll get back here if the new |p| doesn't match */
  948.   }
  949.   if (p==NULL)
  950.     p=q, q=NULL; /* |q| held the other branch of |r| */
  951. }
  952.  
  953. @ @<If no match ...@>=
  954.   if (r==NULL) /* no matches were found */
  955.     return add_section_name(par,c,first,last+1,ispref);
  956.  
  957. @ Although error messages are given in anomalous cases, we do return the
  958. unique best match when a discrepancy is found, because users often
  959. change a title in one place while forgetting to change it elsewhere.
  960.  
  961. @<If one match found, check for compatibility and return match@>=
  962. switch(section_name_cmp(&first,name_len,r)) {
  963.               /* compare all of |r| with new name */
  964.   case prefix:
  965.     if (!ispref) {
  966.       printf("\n! New name is a prefix of <");
  967. @.New name is a prefix...@>
  968.       print_section_name(r);
  969.       err_print(">");
  970.     }
  971.     else if (name_len<prefix_length(r)) set_prefix_length(r,name_len);
  972.     /* fall through */
  973.   case equal: return r;
  974.   case extension: if (!ispref || first<=last)
  975.         extend_section_name(r,first,last+1,ispref);
  976.       return r;
  977.   case bad_extension:
  978.       printf("\n! New name extends <");
  979. @.New name extends...@>
  980.       print_section_name(r);
  981.       err_print(">");
  982.     return r;
  983.   default: /* no match: illegal */
  984.     printf("\n! Section name incompatible with <");
  985. @.Section name incompatible...@>
  986.     print_prefix_name(r);
  987.     printf(">,\n which abbreviates <");
  988.     print_section_name(r);
  989.     err_print(">");
  990.     return r;
  991. }
  992.  
  993. @ The return codes of |section_name_cmp|, which compares a string with
  994. the full name of a section, are those of |web_strcmp| plus
  995. |bad_extension|, used when the string is an extension of a
  996. supposedly already complete section name.  This function has a side
  997. effect when the comparison string is an extension: it advances the
  998. address of the first character of the string by an amount equal to
  999. the length of the known part of the section name.
  1000.  
  1001. The name \.{@@<foo...@@>} should be an acceptable ``abbreviation''
  1002. for \.{@@<foo@@>}. If such an abbreviation comes after the complete
  1003. name, there's no trouble recognizing it. If it comes before the
  1004. complete name, we simply append a null chunk. This logic requires
  1005. us to regard \.{@@<foo...@@>} as an ``extension'' of itself.
  1006.  
  1007. @d bad_extension 5
  1008.  
  1009. @<Predec...@>=
  1010. int section_name_cmp();
  1011.  
  1012. @ @c
  1013. int section_name_cmp(pfirst,len,r)
  1014. char **pfirst; /* pointer to beginning of comparison string */
  1015. int len; /* length of string */
  1016. name_pointer r; /* section name being compared */
  1017. {
  1018.   char *first=*pfirst; /* beginning of comparison string */
  1019.   name_pointer q=r+1; /* access to subsequent chunks */
  1020.   char *ss, *s=first_chunk(r);
  1021.   int c; /* comparison */
  1022.   int ispref; /* is chunk |r| a prefix? */
  1023.   while (1) {
  1024.     ss=(r+1)->byte_start-1;
  1025.     if (*ss==' ' && ss>=r->byte_start) ispref=1,q=q->link;
  1026.     else ispref=0,ss++,q=name_dir;
  1027.     switch(c=web_strcmp(first,len,s,ss-s)) {
  1028.     case equal: if (q==name_dir)
  1029.         if (ispref) {
  1030.           *pfirst=first+(ss-s);
  1031.           return extension; /* null extension */
  1032.         } else return equal;
  1033.       else return (q->byte_start==(q+1)->byte_start)? equal: prefix;
  1034.     case extension:
  1035.       if (!ispref) return bad_extension;
  1036.       first += ss-s;
  1037.       if (q!=name_dir) {len -= ss-s; s=q->byte_start; r=q; continue;}
  1038.       *pfirst=first; return extension;
  1039.     default: return c;
  1040.     }
  1041.   }
  1042. }
  1043.  
  1044. @ The last component of |name_info| is different for \.{CTANGLE} and
  1045. \.{CWEAVE}.  In \.{CTANGLE}, if |p| is a pointer to a section name,
  1046. |p->equiv| is a pointer to its replacement text, an element of the
  1047. array |text_info|.  In \.{CWEAVE}, on the other hand, if
  1048. |p| points to an identifier, |p->xref| is a pointer to its
  1049. list of cross-references, an element of the array |xmem|.  The make-up
  1050. of |text_info| and |xmem| is discussed in the \.{CTANGLE} and \.{CWEAVE}
  1051. source files, respectively; here we just declare a common field
  1052. |equiv_or_xref| as a pointer to a |char|.
  1053.  
  1054. @<More elements of |name...@>=
  1055. char *equiv_or_xref; /* info corresponding to names */
  1056.  
  1057. @** Reporting errors to the user.
  1058. A global variable called |history| will contain one of four values
  1059. at the end of every run: |spotless| means that no unusual messages were
  1060. printed; |harmless_message| means that a message of possible interest
  1061. was printed but no serious errors were detected; |error_message| means that
  1062. at least one error was found; |fatal_message| means that the program
  1063. terminated abnormally. The value of |history| does not influence the
  1064. behavior of the program; it is simply computed for the convenience
  1065. of systems that might want to use such information.
  1066.  
  1067. @d spotless 0 /* |history| value for normal jobs */
  1068. @d harmless_message 1 /* |history| value when non-serious info was printed */
  1069. @d error_message 2 /* |history| value when an error was noted */
  1070. @d fatal_message 3 /* |history| value when we had to stop prematurely */
  1071. @d mark_harmless {if (history==spotless) history=harmless_message;}
  1072. @d mark_error history=error_message
  1073.  
  1074. @<Definit...@>=
  1075. int history=spotless; /* indicates how bad this run was */
  1076.  
  1077. @ The command `|err_print("! Error message")|' will report a syntax error to
  1078. the user, by printing the error message at the beginning of a new line and
  1079. then giving an indication of where the error was spotted in the source file.
  1080. Note that no period follows the error message, since the error routine
  1081. will automatically supply a period. A newline is automatically supplied
  1082. if the string begins with |"|"|.
  1083.  
  1084. @<Predecl...@>=
  1085. void  err_print();
  1086.  
  1087. @ @c
  1088. void
  1089. err_print(s) /* prints `\..' and location of error message */
  1090. char *s;
  1091. {
  1092.   char *k,*l; /* pointers into |buffer| */
  1093.   printf(*s=='!'? "\n%s" : "%s",s);
  1094.   if(web_file_open) @<Print error location based on input buffer@>;
  1095.   update_terminal; mark_error;
  1096. }
  1097.  
  1098. @ The error locations can be indicated by using the global variables
  1099. |loc|, |cur_line|, |cur_file_name| and |changing|,
  1100. which tell respectively the first
  1101. unlooked-at position in |buffer|, the current line number, the current
  1102. file, and whether the current line is from |change_file| or |cur_file|.
  1103. This routine should be modified on systems whose standard text editor
  1104. has special line-numbering conventions.
  1105. @^system dependencies@>
  1106.  
  1107. @<Print error location based on input buffer@>=
  1108. {if (changing && include_depth==change_depth)
  1109.   printf(". (l. %d of change file)\n", change_line);
  1110. else if (include_depth==0) printf(". (l. %d)\n", cur_line);
  1111.   else printf(". (l. %d of include file %s)\n", cur_line, cur_file_name);
  1112. l= (loc>=limit? limit: loc);
  1113. if (l>buffer) {
  1114.   for (k=buffer; k<l; k++)
  1115.     if (*k=='\t') putchar(' ');
  1116.     else putchar(*k); /* print the characters already read */
  1117.   putchar('\n');
  1118.   for (k=buffer; k<l; k++) putchar(' '); /* space out the next line */
  1119. }
  1120. for (k=l; k<limit; k++) putchar(*k); /* print the part not yet read */
  1121. if (*limit=='|') putchar('|'); /* end of \CEE/ text in section names */
  1122. putchar(' '); /* to separate the message from future asterisks */
  1123. }
  1124.  
  1125. @ When no recovery from some error has been provided, we have to wrap
  1126. up and quit as graciously as possible.  This is done by calling the
  1127. function |wrap_up| at the end of the code.
  1128.  
  1129. \.{CTANGLE} and \.{CWEAVE} have their own notions about how to
  1130. print the job statistics.
  1131.  
  1132. @<Prede...@>=
  1133. int wrap_up();
  1134. extern void print_stats();
  1135.  
  1136. @ Some implementations may wish to pass the |history| value to the
  1137. operating system so that it can be used to govern whether or not other
  1138. programs are started. Here, for instance, we pass the operating system
  1139. a status of 0 if and only if only harmless messages were printed.
  1140. @^system dependencies@>
  1141.  
  1142. @c
  1143. int wrap_up() {
  1144.   putchar('\n');
  1145.   if (show_stats)
  1146.     print_stats(); /* print statistics about memory usage */
  1147.   @<Print the job |history|@>;
  1148.   if (history > harmless_message) return(1);
  1149.   else return(0);
  1150. }
  1151.  
  1152. @ @<Print the job |history|@>=
  1153. switch (history) {
  1154. case spotless: if (show_happiness) printf("(No errors were found.)\n"); break;
  1155. case harmless_message:
  1156.   printf("(Did you see the warning message above?)\n"); break;
  1157. case error_message:
  1158.   printf("(Pardon me, but I think I spotted something wrong.)\n"); break;
  1159. case fatal_message: printf("(That was a fatal error, my friend.)\n");
  1160. } /* there are no other cases */
  1161.  
  1162. @ When there is no way to recover from an error, the |fatal| subroutine is
  1163. invoked. This happens most often when |overflow| occurs.
  1164.  
  1165. @<Predec...@>=
  1166. void fatal(), overflow();
  1167.  
  1168. @ The two parameters to |fatal| are strings that are essentially
  1169. concatenated to print the final error message.
  1170.  
  1171. @c void
  1172. fatal(s,t)
  1173.   char *s,*t;
  1174. {
  1175.   if (*s) printf(s);
  1176.   err_print(t);
  1177.   history=fatal_message; exit(wrap_up());
  1178. }
  1179.  
  1180. @ An overflow stop occurs if \.{CWEB}'s tables aren't large enough.
  1181.  
  1182. @c void
  1183. overflow(t)
  1184.   char *t;
  1185. {
  1186.   printf("\n! Sorry, %s capacity exceeded",t); fatal("","");
  1187. }
  1188. @.Sorry, capacity exceeded@>
  1189.  
  1190. @ Sometimes the program's behavior is far different from what it should be,
  1191. and \.{CWEB} prints an error message that is really for the \.{CWEB}
  1192. maintenance person, not the user. In such cases the program says
  1193. |confusion("indication of where we are")|.
  1194.  
  1195. @d confusion(s) fatal("! This can't happen: ",s)
  1196. @.This can't happen@>
  1197.  
  1198. @** Command line arguments.
  1199. The user calls \.{CWEAVE} and \.{CTANGLE} with arguments on the command line.
  1200. These are either file names or flags to be turned off (beginning with |"-"|)
  1201. or flags to be turned on (beginning with |"+"|.
  1202. The following globals are for communicating the user's desires to the rest
  1203. of the program. The various file name variables contain strings with
  1204. the names of those files. Most of the 128 flags are undefined but available
  1205. for future extensions.
  1206.  
  1207. @d show_banner flags['b'] /* should the banner line be printed? */
  1208. @d show_progress flags['p'] /* should progress reports be printed? */
  1209. @d show_stats flags['s'] /* should statistics be printed at end of run? */
  1210. @d show_happiness flags['h'] /* should lack of errors be announced? */
  1211.  
  1212. @<Defin...@>=
  1213. int argc; /* copy of |ac| parameter to |main| */
  1214. char **argv; /* copy of |av| parameter to |main| */
  1215. char C_file_name[max_file_name_length]; /* name of |C_file| */
  1216. char tex_file_name[max_file_name_length]; /* name of |tex_file| */
  1217. char idx_file_name[max_file_name_length]; /* name of |idx_file| */
  1218. char scn_file_name[max_file_name_length]; /* name of |scn_file| */
  1219. boolean flags[128]; /* an option for each 7-bit code */
  1220.  
  1221. @ The |flags| will be initially zero. Some of them are set to~1 before
  1222. scanning the arguments; if additional flags are 1 by default they
  1223. should be set before calling |common_init|.
  1224.  
  1225. @<Set the default options common to \.{CTANGLE} and \.{CWEAVE}@>=
  1226. show_banner=show_happiness=show_progress=1;
  1227.  
  1228. @ We now must look at the command line arguments and set the file names
  1229. accordingly.  At least one file name must be present: the \.{CWEB}
  1230. file.  It may have an extension, or it may omit the extension to get |".w"| or
  1231. |".web"| added.  The \TEX/ output file name is formed by replacing the \.{CWEB}
  1232. file name extension by |".tex"|, and the \CEE/ file name by replacing
  1233. the extension by |".c"|, after removing the directory name (if any).
  1234.  
  1235. If there is a second file name present among the arguments, it is the
  1236. change file, again either with an extension or without one to get |".ch"|.
  1237. An omitted change file argument means that |"/dev/null"| should be used,
  1238. when no changes are desired.
  1239. @^system dependencies@>
  1240.  
  1241. If there's a third file name, it will be the output file.
  1242.  
  1243. @<Pred...@>=
  1244. void scan_args();
  1245.  
  1246. @ @c
  1247. void
  1248. scan_args()
  1249. {
  1250.   char *dot_pos; /* position of |'.'| in the argument */
  1251.   char *name_pos; /* file name beginning, sans directory */
  1252.   register char *s; /* register for scanning strings */
  1253.   boolean found_web=0,found_change=0,found_out=0;
  1254.              /* have these names have been seen? */
  1255.   boolean flag_change;
  1256.  
  1257.   while (--argc > 0) {
  1258.     if ((**(++argv)=='-'||**argv=='+')&&*(*argv+1)) @<Handle flag argument@>@;
  1259.     else {
  1260.       s=name_pos=*argv;@+dot_pos=NULL;
  1261.       while (*s) {
  1262.         if (*s=='.') dot_pos=s++;
  1263.         else if (*s=='/') dot_pos=NULL,name_pos=++s;
  1264.         else s++;
  1265.       }
  1266.       if (!found_web) @<Make
  1267.        |web_file_name|, |tex_file_name| and |C_file_name|@>@;
  1268.       else if (!found_change) @<Make |change_file_name| from |fname|@>@;
  1269.       else if (!found_out) @<Override |tex_file_name| and |C_file_name|@>@;
  1270.         else @<Print usage error message and quit@>;
  1271.     }
  1272.   }
  1273.   if (!found_web) @<Print usage error message and quit@>;
  1274.   if (found_change<=0) strcpy(change_file_name,"/dev/null");
  1275. }
  1276.  
  1277. @ We use all of |*argv| for the |web_file_name| if there is a |'.'| in it,
  1278. otherwise we add |".w"|. If this file can't be opened, we prepare an
  1279. |alt_web_file_name| by adding |"web"| after the dot.
  1280. The other file names come from adding other things
  1281. after the dot.  We must check that there is enough room in
  1282. |web_file_name| and the other arrays for the argument.
  1283.  
  1284. @<Make |web_file_name|...@>=
  1285. {
  1286.   if (s-*argv > max_file_name_length-5)
  1287.     @<Complain about argument length@>;
  1288.   if (dot_pos==NULL)
  1289.     sprintf(web_file_name,"%s.w",*argv);
  1290.   else {
  1291.     strcpy(web_file_name,*argv);
  1292.     *dot_pos=0; /* string now ends where the dot was */
  1293.   }
  1294.   sprintf(alt_web_file_name,"%s.web",*argv);
  1295.   sprintf(tex_file_name,"%s.tex",name_pos); /* strip off directory name */
  1296.   sprintf(idx_file_name,"%s.idx",name_pos);
  1297.   sprintf(scn_file_name,"%s.scn",name_pos);
  1298.   sprintf(C_file_name,"%s.c",name_pos);
  1299.   found_web=1;
  1300. }
  1301.  
  1302. @ @<Make |change_file_name|...@>=
  1303. {
  1304.   if (strcmp(*argv,"-")==0) found_change=-1;
  1305.   else {
  1306.     if (s-*argv > max_file_name_length-4)
  1307.       @<Complain about argument length@>;
  1308.     if (dot_pos==NULL)
  1309.       sprintf(change_file_name,"%s.ch",*argv);
  1310.     else strcpy(change_file_name,*argv);
  1311.     found_change=1;
  1312.   }
  1313. }
  1314.  
  1315. @ @<Override...@>=
  1316. {
  1317.   if (s-*argv > max_file_name_length-5)
  1318.     @<Complain about argument length@>;
  1319.   if (dot_pos==NULL) {
  1320.     sprintf(tex_file_name,"%s.tex",*argv);
  1321.     sprintf(idx_file_name,"%s.idx",*argv);
  1322.     sprintf(scn_file_name,"%s.scn",*argv);
  1323.     sprintf(C_file_name,"%s.c",*argv);
  1324.   } else {
  1325.     strcpy(tex_file_name,*argv);
  1326.     if (flags['x']) { /* indexes will be generated */
  1327.       if (program==cweave && strcmp(*argv+strlen(*argv)-4,".tex")!=0)
  1328.         fatal("! Output file name should end with .tex\n",*argv);
  1329. @.Output file name...tex@>
  1330.       strcpy(idx_file_name,*argv);
  1331.       strcpy(idx_file_name+strlen(*argv)-4,".idx");
  1332.       strcpy(scn_file_name,*argv);
  1333.       strcpy(scn_file_name+strlen(*argv)-4,".scn");
  1334.     }
  1335.     strcpy(C_file_name,*argv);
  1336.   }
  1337.   found_out=1;
  1338. }
  1339.  
  1340. @ @<Handle flag...@>=
  1341. {
  1342.   if (**argv=='-') flag_change=0;
  1343.   else flag_change=1;
  1344.   for(dot_pos=*argv+1;*dot_pos>'\0';dot_pos++)
  1345.     flags[*dot_pos]=flag_change;
  1346. }
  1347.  
  1348. @ @<Print usage error message and quit@>=
  1349. {
  1350. if (program==ctangle)
  1351.   fatal(
  1352. "! Usage: ctangle [options] webfile[.w] [{changefile[.ch]|-} [outfile[.c]]]\n"
  1353.    ,"");
  1354. @.Usage:@>
  1355. else fatal(
  1356. "! Usage: cweave [options] webfile[.w] [{changefile[.ch]|-} [outfile[.tex]]]\n"
  1357.    ,"");
  1358. }
  1359.  
  1360. @ @<Complain about arg...@>= fatal("! Filename too long\n", *argv);
  1361. @.Filename too long@>
  1362.  
  1363. @** Output. Here is the code that opens the output file:
  1364. @^system dependencies@>
  1365.  
  1366. @<Defin...@>=
  1367. FILE *C_file; /* where output of \.{CTANGLE} goes */
  1368. FILE *tex_file; /* where output of \.{CWEAVE} goes */
  1369. FILE *idx_file; /* where index from \.{CWEAVE} goes */
  1370. FILE *scn_file; /* where list of sections from \.{CWEAVE} goes */
  1371. FILE *active_file; /* currently active file for \.{CWEAVE} output */
  1372.  
  1373. @ @<Scan arguments and open output files@>=
  1374. scan_args();
  1375. if (program==ctangle) {
  1376.   if ((C_file=fopen(C_file_name,"w"))==NULL)
  1377.     fatal("! Cannot open output file ", C_file_name);
  1378. @.Cannot open output file@>
  1379. }
  1380. else {
  1381.   if ((tex_file=fopen(tex_file_name,"w"))==NULL)
  1382.     fatal("! Cannot open output file ", tex_file_name);
  1383. }
  1384.  
  1385. @ The |update_terminal| procedure is called when we want
  1386. to make sure that everything we have output to the terminal so far has
  1387. actually left the computer's internal buffers and been sent.
  1388. @^system dependencies@>
  1389.  
  1390. @d update_terminal fflush(stdout) /* empty the terminal output buffer */
  1391.  
  1392. @ Terminal output uses |putchar| and |putc| when we have to
  1393. translate from \.{CWEB}'s code into the external character code,
  1394. and |printf| when we just want to print strings.
  1395. Several macros make other kinds of output convenient.
  1396. @^system dependencies@>
  1397. @d new_line putchar('\n') @d putxchar putchar
  1398. @d term_write(a,b) fflush(stdout),fwrite(a,sizeof(char),b,stdout)
  1399. @d C_printf(c,a) fprintf(C_file,c,a)
  1400. @d C_putc(c) putc(c,C_file) /* isn't \CEE/ wonderfully consistent? */
  1401.  
  1402. @ We predeclare several standard system functions here instead of including
  1403. their system header files, because the names of the header files are not as
  1404. standard as the names of the functions. (For example, some \CEE/ environments
  1405. have \.{<string.h>} where others have \.{<strings.h>}.)
  1406.  
  1407. @<Predecl...@>=
  1408. extern int strlen(); /* length of string */
  1409. extern int strcmp(); /* compare strings lexicographically */
  1410. extern char* strcpy(); /* copy one string to another */
  1411. extern int strncmp(); /* compare up to $n$ string characters */
  1412. extern char* strncpy(); /* copy up to $n$ string characters */
  1413.  
  1414. @** Index.
  1415.